<template>
  <div>
    <div class="treebox">
      <el-tree :data="treeData"
      default-expand-all
      :props="defaultProps"
      show-checkbox
      :check-strictly="true"
      :highlight-current="true"
      
      @node-click="handleNodeClick"></el-tree>
    </div>
    <el-button @click="handleAdd" v-if="!isShowEditDeleBtn">新增</el-button>
    <el-button @click="handleQueck">快速关联</el-button>
    <el-button @click="handleEdit" >编辑</el-button>
    <el-button @click="handleDelete" >删除</el-button>
    <el-button @click="handleSearch">查找节点</el-button>
    <br />
    <hr >

    <div v-for="(item, index) in selectDataList" :key="index">
      <el-select v-model="item.value" placeholder="请选择" @change="handleChange">
        <el-option
          v-for="item in item.list"
          :key="item.id"
          :label="item.label"
          :value="item.id">
        </el-option>
      </el-select>
    </div>
    <textarea class="my_editor" id="Editortigan" v-model="Editortext"></textarea>
    <div class="hello"></div> 
  </div>
</template>

<script>
import dataList from '@/utils/data'
import { clone, typeOf } from '@/utils/common.js'
import tinymce from '@/components/tinymce';
export default {
  components: {
    tinymce
  },
  data () {
    return {
      Editortext: '',
      content: '',
      isShow: true,
      selectAry: [],
      selectModel: '',
      selectModelAry: [],
      selectDataList: [],
      treeData: [
        {
        id: 1,
        label: '一级 1',
        children: [
          {
            id: 22,
            label: '添加',
            children: [
              {
                id: 25,
                label: '添加'
              }
            ]
          },
          {
            id: 23,
            label: '添加'
          }
        ]
      },
      {
        id: 2,
        label: '一级 2'
      },
      {
        id: 3,
        label: '一级 3'
      }
      ],
      id: 10,
      topid: '',
      originAry: [],
      selectCurrentObj: {},
      selectParentObj: [],
      isShowEditDeleBtn: false,
      copySelectAry: [],
      defaultProps: {
        label: 'label',
        children: 'children'
      },
      maxnum: ''
    }
  },
  methods: {
    tigan (val) {
      console.log(val)
    },
    getChildAry (ary, id) {
      let row = {}
      for(let i=0; i<ary.length; i++) {
        if (ary[i].id === id) {
          row = ary[i]
          break;
        } else if (ary[i].children && ary[i].children.length > 0) {
          row = this.getChildAry(ary[i].children, id)
        }
      }
      return row
    },
    getFatherId (ary, result) {
      for (let i=0; i<ary.length; i++) {
        result.push(ary[i].level)
        if (ary[i].children && ary[i].children.length >0) {
          this.getFatherId(ary[i].children, result)
        }
      }
    },
    // 下拉框 展示
    handleChange (val) {
      let row = this.getChildAry(this.selectModelAry, val)
      if (row.level === 1) {
        let result = []
        this.getFatherId([row], result)
        this.maxnum = Math.max(...result)
      }
      if (!row.children && row.level === 1){
        let ary = []
        ary.push({
          value: val,
          list: this.selectModelAry
        })
        this.selectDataList = ary
        return
      } else if (!row.children && row.level != this.maxnum) {
        this.selectDataList.pop()
      }
      if (row.children && row.children.length > 0) {
        let ary = row.children ? row.children : []
        this.selectDataList.push({
          value: '',
          list: ary
        })
      }
    },
    handleChildMo (val) {

    },
    handleSearch () {
      let ary = this.getParents(this.treeData, this.selectCurrentObj.id)
      this.topid = ary.length-1
    },

    getParents(data, id) {
      for (var i in data) {
        if (data[i].id == id) {
          return [data[i].id];
        }
        if (data[i].children) {
          var ro = this.getParents(data[i].children, id);
          if (ro !== undefined) {
            return ro.concat(data[i].id);
          }
        }
      }
    },
    judgeHowMach (row) {
      for (let j=0; j<row.length; j++) {
        if (row[j].children && row[j].children.length > 0) {
          this.judgeHowMach(row[j].children)
        } else {
          console.log(j)
        }
      }
    },
    addInxTree (ary, inx) {
      ary.forEach(item => {
        if (!item.level) {
          item.level = inx
        }
        if (item.children && item.children.length > 0) {
          inx++
          this.addInxTree(item.children, inx)
          inx--
        }
      })
    },
    addTreeNode (ary, level, addnode) {
      let levelFlag = false
      ary.map(item => {
        if (item.level === level) {
            addnode.level = level + 1
          console.log({...addnode})
          this.addNodeTem(item, {...addnode})
          
        }
        if (item.children && item.children.length > 0) {
          this.addTreeNode(item.children, level, addnode)
        }
      })
    },
    addNodeTem (obj, addnode) {
      if (!obj.children) {
          this.$set(obj, 'children', [])
        }
        obj.children.push(addnode)
        
    },
    handleQueck () {
      this.addInxTree(this.treeData, 1)
      let obj = {
        id: '199',
        label: '添加元素'
      }
      this.addTreeNode(this.treeData, this.selectParentObj.level, obj)
    },
    handleAdd () {
      let obj = {
          "id": 40,
          "label": '四十级 1-1',
        }
      if (!this.selectCurrentObj.children) {
          this.$set(this.selectCurrentObj, 'children', [])
        }
        this.selectCurrentObj.children.push(obj)
    },
    handleEdit () {

    },
    handleDelete () {
      let parent = this.selectParentObj.parent
      let children = parent.data.children || parent.data
      let index = children.findIndex(d => d.code === this.selectCurrentObj.code)
      console.log(index)
      children.splice(index, 1)
    },
    handleNodeClick (val, node, cur) {
      this.selectCurrentObj = val
      this.selectParentObj = node
      console.log(val, node)
    },
    tinymcetigan () {
      let _this = this;
      _this.$tinymce.baseURL = './static/tinymce';
      _this.$tinymce
        .init({
          selector: '#Editortigan',
          language_url: './static/tinymce/zh_CN.js', // 设置中文
          skin_url: '/static/tinymce/skins/ui/oxide',
          language: 'zh_CN',
          // plugins: [
            // 配置插件：可自己随意选择，但如果是上传本地图片image和imagetools是必要的
            // 'lists image media table wordcount code fullscreen help  toc fullpage autosave nonbreaking insertdatetime visualchars visualblocks searchreplace spellchecker pagebreak link charmap paste print preview hr anchor'
          // ], // 工具框，也可自己随意配置
          // toolbar:
          //   'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image ',
          // toolbar: [
            // 'undo redo | formatselect | cut copy selectall| bold italic underline strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat code  bullist numlist | lists image table | searchreplace preview hr'
            // 'newdocument undo redo | formatselect visualaid|cut copy paste selectall| bold italic underline strikethrough |codeformat blockformats| superscript subscript  | forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |  removeformat code  bullist numlist | lists image media table link |fullscreen help toc fullpage restoredraft | nonbreaking insertdatetime visualchars | visualblocks searchreplace spellchecker pagebreak anchor charmap | pastetext print preview hr'
          // ],
          // file_picker_types: 'media',
          // file_picker_callback: (cb, value, meta) => { // 配置 将在图片、媒体、链接对话框中加入上传文件回调
          //   // 当点击meidia图标上传时,判断meta.filetype == 'media'有必要，因为file_picker_callback是media(媒体)、image(图片)、file(文件)的共同入口
          //   if (meta.filetype === 'media') {
          //     // 创建一个隐藏的type=file的文件选择input
          //     let input = document.createElement('input');
          //     input.setAttribute('type', 'file');
          //     input.onchange = function () {
          //       const file = this.files[0]; // 只选取第一个文件。如果要选取全部，后面注意做修改
          //       let xhr, formData;
          //       xhr = new XMLHttpRequest();
          //       xhr.open('POST', baseurl + '/fileApi/fileOperations/upload');
          //       xhr.withCredentials = self.credentials;
          //       xhr.upload.onprogress = function (e) {
          //         // 进度(e.loaded / e.total * 100)
          //         let percent = e.loaded / e.total * 100;
          //         if (percent < 100) {
          //           _this.$tinymce.activeEditor.setProgressState(true); // 是否显示loading状态：1（显示）0（隐藏）
          //         } else {
          //           _this.$tinymce.activeEditor.setProgressState(false);
          //           // return
          //         }
          //       };
          //       xhr.onerror = function () {
          //         console.log(xhr.status);
          //         _this.$tinymce.activeEditor.setProgressState(false);
          //       };
          //       xhr.onload = function () {
          //         let json;
          //         if (xhr.status < 200 || xhr.status >= 300) {
          //           console.log('HTTP 错误: ' + xhr.status);
          //           return;
          //         }
          //         json = JSON.parse(xhr.responseText);
          //         // 假设接口返回JSON数据为{status: 0, msg: "上传成功", data: {location: "/localImgs/1546434503854.mp4"}}
          //         if (json.code === 200) {
          //           // 接口返回的文件保存地址
          //           console.log(json);
          //           let mediaLocation = baseurl + '/' + json.data.fileId;
          //           // cb()回调函数，将mediaLocation显示在弹框输入框中
          //           cb(mediaLocation, { title: file.name });
          //         } else {
          //           console.log(json.msg);
          //           // return
          //         }
          //       };
          //       formData = new FormData();
          //       // 假设接口接收参数为file,值为选中的文件
          //       formData.append('file', file);
          //       // 正式使用将下面被注释的内容恢复
          //       xhr.send(formData);
          //     };
          //     // 触发点击
          //     input.click();
          //   }
          // },
          // image_advtab: true,
          // table_default_styles: {
          //   width: '100%',
          //   borderCollapse: 'collapse'
          // },
          // image_title: false, // 是否开启图片标题设置的选择，这里设置否
          // automatic_uploads: true, // 图片异步上传处理函数
          // imageupload_url: baseurl + '/fileApi/fileOperations/upload',
          // images_upload_handler: (blobInfo, success, failure) => { // 图片上传方法
          //   // var formData=new FormData();
          //   var uploaddatas = {};
          //   // debugger
          //   uploaddatas.ts = Date.now();
          //   // uploaddatas.signature = hmacsha1(
          //   //   baseurl.hmacsha1value,
          //   //   'ts=' + uploaddatas.ts
          //   // )
          //   var xhr, formData;
          //   xhr = new XMLHttpRequest();
          //   xhr.withCredentials = false;
          //   xhr.open(
          //     'POST',
          //     baseurl + '/fileApi/fileOperations/upload'
          //   );
          //   formData = new FormData();
          //   formData.append('file', blobInfo.blob());
          //   formData.append('ts', uploaddatas.ts);
          //   // formData.append('signature', uploaddatas.signature)
          //   xhr.onload = function (e) {
          //     var json;

          //     if (xhr.status !== 200) {
          //       failure('HTTP Error: ' + xhr.status);
          //       return;
          //     }
          //     json = JSON.parse(this.responseText);

          //     if (!json || typeof json.data.fileId !== 'string') {
          //       failure('Invalid JSON: ' + xhr.responseText);
          //       return;
          //     }
          //     success(baseurl + '/' + json.data.fileId);
          //   };
          //   xhr.send(formData);
          // },
          // init_instance_callback: function (editor) { // 初始化结束后 执行
          // console.log(editor, 99)
          //   editor.on('NodeChange Change input KeyUp', () => {
          //     // 获取富文本编辑器里面的内容
          //     _this.Editortext = editor.getContent();
          //     if (_this.Editortext.length > 60000) {
          //       _this.$message.error('字符数过长');
          //       return;
          //     }
          //     _this.$emit('tigan', _this.Editortext);
          //   });
          // }
        })
        .then(resolve => {
          console.log(this);
          console.log(resolve);
          // 初始化富文本编辑器里面的内容
          resolve[0].setContent(_this.Editortext);
        });
    }

  },
  mounted() {
    this.tinymcetigan();
  },
  created () {
    // this.addInxTree(this.treeData, 1)
    // this.originAry = dataList.data
    // let ary = []
    // this.originAry.map(k => {
    //   k.tagEnumList.map(j => {
    //     ary.push(j)
    //   })
    // })
    // console.log(this.originAry)
    // this.treeData = ary
    let selectModelAry = [
        {
        id: 1,
        label: '一级 1',
        children: [
          {
            id: 22,
            label: '添加',
            children: [
              {
                id: 25,
                label: '添加'
              }
            ]
          },
          {
            id: 23,
            label: '添加'
          }
        ]
      },
      {
        id: 2,
        label: '一级 2'
      },
      {
        id: 3,
        label: '一级 3'
      }
      ];
    this.addInxTree(selectModelAry, 1)
    this.selectDataList.push({
      value: '',
      list: selectModelAry
    })
    this.selectModelAry = selectModelAry
    console.log(this.selectModelAry)
  }
}
</script>

<style lang="scss">
@import "./index.scss";
.treebox{
  width: 20%;
}
</style>